import {resolve} from 'path';
import {defineConfig, loadEnv} from 'vite';
import vue from '@vitejs/plugin-vue';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import {ElementPlusResolver} from 'unplugin-vue-components/resolvers';

// https://vite.dev/config/
export default ({mode}) => {
    const env = loadEnv(mode, process.cwd());
    return defineConfig({
        base: '/',
        server: {
            host: true,
            open: true,
            proxy: {
                '/api': {
                    target: env.VITE_REQUEST_URL,
                    changeOrigin: true,
                    rewrite: (path) => path.replace(/^\/api/, ''),
                }
            }
        },
        resolve: {
            alias: {
                '@': resolve(__dirname, './src')
            },
        },
        esbuild: {
            drop: ['console', 'debugger'],
            minifyIdentifiers: true,
            minifySyntax: true,
            minifyWhitespace: true,
            treeShaking: true,
            sourcemap: false,
            format: 'esm'
        },
        build: {
            outDir: 'dist',
            assetsDir: 'static',
            cssCodeSplit: true,
            sourcemap: false,
            rollupOptions: {
                output: {
                    manualChunks: (id) => {
                        if (id.includes('node_modules')) {
                            if (id.includes('axios')) {
                                return 'axios';
                            }
                            if (id.includes('vue-router')) {
                                return 'vueRouter';
                            }
                            if (id.includes('js-md5')) {
                                return 'md5';
                            }
                        }
                    },
                    chunkFileNames: 'static/js/[name]-[hash].js',
                    entryFileNames: 'static/js/[name]-[hash].js',
                    assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
                }
            }
        },
        plugins: [vue(), AutoImport({
            resolvers: [ElementPlusResolver()],
        }), Components({
            resolvers: [ElementPlusResolver()],
        })],
    });
}
